// 监控页面主逻辑

/**
 * 监控应用主类
 */
class MonitorApp {
    constructor() {
        this.config = {
            refreshIntervals: {
                province: 5 * 60 * 1000,    // 省份环比：5分钟
                transaction: 60 * 1000,     // 交易量：1分钟
                failCode: 60 * 1000         // 失败码：1分钟
            },
            apiEndpoints: {
                province: '/api/tranvolume/province/compare',
                transaction: '/api/tranvolume/transaction/realtime',
                failCode: '/api/tranvolume/fail-code/trend'
            }
        };
        
        this.timers = {};
        this.mockData = this.initMockData();
        this.isUsingMockData = true;
        this.selectedProvinces = []; // 存储选中的省份
        
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            showLoading(true);
            
            // 初始化时间显示
            this.initTimeDisplay();
            
            // 初始化基准时间为当前时间
            this.initBaseTime();
            
            // 初始化省份选择器
            this.initProvinceSelector();
            
            // 初始化事件监听
            this.initEventListeners();
            
            // 检查API可用性
            await this.checkApiAvailability();
            
            // 加载初始数据
            await this.loadAllData();
            
            // 启动定时刷新
            this.startAutoRefresh();
            
            showLoading(false);
            updateStatus('success', '系统运行正常');
            
            log('info', '监控系统初始化完成');
        } catch (error) {
            handleError(error, '系统初始化');
            showLoading(false);
        }
    }

    /**
     * 初始化基准时间
     */
    initBaseTime() {
        const now = new Date();
        const timeString = now.toISOString().slice(0, 16); // 格式化为 YYYY-MM-DDTHH:mm
        $('#provinceBaseTime').val(timeString);
    }


    /**
     * 初始化模拟数据
     */
    initMockData() {
        return {
            province: this.generateProvinceCompareData(),
            transaction: {
                totalData: this.generateTimeSeriesData(60, 30000, 50000),
                successData: this.generateTimeSeriesData(60, 29000, 49000),
                failData: this.generateTimeSeriesData(60, 500, 2000),
                currentVolume: 45200,
                currentSuccessRate: 98.5,
                updateTime: '2025-09-07 14:30:15'
            },
            failCodes: {
                failCodes: [
                    { retCode: 'Z00000', retDesc: '系统异常', failCount: 1250, failRate: 0.85 },
                    { retCode: '110022', retDesc: '网络超时', failCount: 890, failRate: 0.61 },
                    { retCode: '999999', retDesc: '未知错误', failCount: 567, failRate: 0.39 },
                    { retCode: '888888', retDesc: '数据库连接失败', failCount: 234, failRate: 0.16 },
                    { retCode: '777777', retDesc: '服务不可用', failCount: 123, failRate: 0.08 }
                ],
                timeData: this.generateTimeSeriesData(24, 0, 0, true),
                updateTime: '2025-09-07 14:30:15'
            }
        };
    }

    /**
     * 生成省份环比对比数据（按日期）
     */
    generateProvinceCompareData() {
        const provinces = [
            { provCode: '11', provName: '北京' },
            { provCode: '12', provName: '天津' },
            { provCode: '13', provName: '河北' },
            { provCode: '14', provName: '山西' },
            { provCode: '15', provName: '内蒙古' }
        ];

        // 生成7天的数据（默认对比天数）
        const dateData = [];
        const baseDate = new Date('2025-09-07T21:30:00');
        
        for (let i = 6; i >= 0; i--) {
            const currentDate = new Date(baseDate.getTime() - i * 24 * 60 * 60 * 1000);
            const dateStr = currentDate.toLocaleDateString('zh-CN', { 
                month: '2-digit', 
                day: '2-digit' 
            });
            
            // 为每个日期生成各省份的交易量数据
            const provinceData = provinces.map(prov => ({
                provCode: prov.provCode,
                provName: prov.provName,
                value: Math.floor(Math.random() * 2000) + 800 + i * 50 // 模拟趋势变化
            }));

            dateData.push({
                date: dateStr,
                provinceData: provinceData
            });
        }

        return {
            provinces: provinces,
            dateData: dateData,
            updateTime: '2025-09-07 21:30:15'
        };
    }

    /**
     * 生成时间序列数据
     */
    generateTimeSeriesData(count, minValue, maxValue, isHourly = false) {
        const data = [];
        const now = new Date();
        const interval = isHourly ? 3600000 : 60000; // 1小时或1分钟间隔
        
        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now.getTime() - i * interval);
            const timeStr = isHourly ? 
                time.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit' }) :
                time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            
            if (minValue === 0 && maxValue === 0) {
                data.push({ time: timeStr });
            } else {
                const value = Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
                data.push({
                    time: timeStr,
                    value: value,
                    successRate: 90 + Math.random() * 10 // 调整为90%-100%之间，变化更明显
                });
            }
        }
        
        return data;
    }

    /**
     * 生成成功率数据
     */
    generateSuccessRateData(count) {
        const data = [];
        const now = new Date();
        
        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now.getTime() - i * 60000);
            const rate = 96 + Math.random() * 4; // 96%-100%之间
            data.push({
                time: time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
                value: rate
            });
        }
        
        return data;
    }

    /**
     * 初始化省份选择器
     */
    initProvinceSelector() {
        // 默认选择前5个省份
        const defaultProvinces = getAllProvinces().slice(0, 5);
        this.selectedProvinces = defaultProvinces.map(p => p.code);
        this.updateProvinceDisplay();
        this.renderProvinceGrid();
    }

    /**
     * 渲染省份网格
     */
    renderProvinceGrid(provinces = null) {
        const provinceList = provinces || getAllProvinces();
        const grid = $('#provinceGrid');
        grid.empty();
        
        provinceList.forEach(province => {
            const isSelected = this.selectedProvinces.includes(province.code);
            const isDisabled = !isSelected && this.selectedProvinces.length >= 5;
            
            const item = $(`
                <div class="province-item ${isSelected ? 'selected' : ''} ${isDisabled ? 'disabled' : ''}" 
                     data-code="${province.code}">
                    ${province.name}
                </div>
            `);
            
            if (!isDisabled) {
                item.on('click', () => this.toggleProvince(province.code));
            }
            
            grid.append(item);
        });
    }

    /**
     * 切换省份选择状态
     */
    toggleProvince(provinceCode) {
        const index = this.selectedProvinces.indexOf(provinceCode);
        
        if (index > -1) {
            // 取消选择
            this.selectedProvinces.splice(index, 1);
        } else {
            // 选择省份
            if (this.selectedProvinces.length < 5) {
                this.selectedProvinces.push(provinceCode);
            }
        }
        
        this.updateModalDisplay();
        this.renderProvinceGrid();
    }

    /**
     * 更新省份显示
     */
    updateProvinceDisplay() {
        const count = this.selectedProvinces.length;
        $('#selectedProvinceCount').text(count);
        
        const provincesList = $('#selectedProvincesList');
        provincesList.empty();
        
        this.selectedProvinces.forEach(code => {
            const provinceName = getProvinceName(code);
            const tag = $(`
                <span class="province-tag">
                    ${provinceName}
                    <button class="remove-btn" data-code="${code}">×</button>
                </span>
            `);
            
            tag.find('.remove-btn').on('click', (e) => {
                e.stopPropagation();
                this.removeProvince(code);
            });
            
            provincesList.append(tag);
        });
    }

    /**
     * 移除省份
     */
    removeProvince(provinceCode) {
        const index = this.selectedProvinces.indexOf(provinceCode);
        if (index > -1) {
            this.selectedProvinces.splice(index, 1);
            this.updateProvinceDisplay();
            this.loadProvinceData(); // 重新加载数据
        }
    }

    /**
     * 更新模态框显示
     */
    updateModalDisplay() {
        $('#modalSelectedCount').text(this.selectedProvinces.length);
        
        const selectedNames = this.selectedProvinces.map(code => getProvinceName(code));
        $('#modalSelectedList').text(selectedNames.length > 0 ? selectedNames.join(', ') : '无');
    }
    initTimeDisplay() {
        const updateTime = () => {
            $('#currentTime').text(getCurrentTimeString());
        };
        
        updateTime();
        setInterval(updateTime, 1000);
    }

    /**
     * 初始化事件监听
     */
    initEventListeners() {
        // 省份环比查询条件
        $('#provinceBaseTime').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceTimeRange').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceCompareDays').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));
        
        $('#provinceCenterSelect').on('change', debounce(async (e) => {
            await this.loadProvinceData();
        }, 300));

        // 省份选择相关事件
        $('#provinceSearch').on('input', debounce((e) => {
            const keyword = e.target.value;
            const filteredProvinces = searchProvinces(keyword);
            this.renderProvinceGrid(filteredProvinces);
        }, 300));

        $('#confirmProvinceSelection').on('click', () => {
            this.updateProvinceDisplay();
            $('#provinceModal').modal('hide');
            this.loadProvinceData(); // 重新加载数据
        });

        // 模态框显示时更新状态
        $('#provinceModal').on('shown.bs.modal', () => {
            this.updateModalDisplay();
            $('#provinceSearch').val('').focus();
            this.renderProvinceGrid();
        });

        // 交易量监控查询条件
        $('#transactionTimeRange').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionCenterSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionServicePlatSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));
        
        $('#transactionChelCodeSelect').on('change', debounce(async (e) => {
            await this.loadTransactionData();
        }, 300));

        // 失败响应码查询条件
        $('#failCodeTimeRange').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeLimit').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeCenterSelect').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));
        
        $('#failCodeServicePlatSelect').on('change', debounce(async (e) => {
            await this.loadFailCodeData();
        }, 300));

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAutoRefresh();
            } else {
                this.resumeAutoRefresh();
            }
        });
    }

    /**
     * 检查API可用性
     */
    async checkApiAvailability() {
        try {
            // 尝试调用健康检查接口
            const response = await $.ajax({
                url: '/api/tranvolume/health',
                method: 'GET',
                timeout: 3000
            });
            
            if (response && response.success) {
                this.isUsingMockData = false;
                log('info', 'API服务可用，使用真实数据');
                updateStatus('success', 'API连接正常');
            } else {
                throw new Error('API响应异常');
            }
        } catch (error) {
            this.isUsingMockData = true;
            log('warn', 'API服务不可用，使用模拟数据', error);
            updateStatus('error', '使用模拟数据');
        }
    }

    /**
     * 加载所有数据
     */
    async loadAllData() {
        const loadPromises = [
            this.loadProvinceData(),
            this.loadTransactionData(),
            this.loadFailCodeData()
        ];

        try {
            await Promise.all(loadPromises);
            log('info', '所有监控数据加载完成');
        } catch (error) {
            handleError(error, '数据加载');
        }
    }

    /**
     * 刷新所有数据
     */
    async refreshAllData() {
        await this.loadAllData();
    }

    /**
     * 加载省份交易量环比数据
     */
    async loadProvinceData() {
        try {
            const baseTime = $('#provinceBaseTime').val();
            const timeRange = parseInt($('#provinceTimeRange').val()) || 60;
            const compareDays = parseInt($('#provinceCompareDays').val()) || 7;
            const center = $('#provinceCenterSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                // 根据参数生成动态数据
                data = this.generateDynamicProvinceData(baseTime, timeRange, compareDays);
            } else {
                const params = { 
                    baseTime, 
                    timeRange, 
                    compareDays, 
                    provinceCodes: this.selectedProvinces.join(','), 
                    center 
                };
                const response = await $.ajax({
                    url: this.config.apiEndpoints.province,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            createProvinceCompareChart('provinceChart', data);
            log('info', '省份交易量数据更新完成');
        } catch (error) {
            handleError(error, '省份交易量数据加载');
        }
    }

    /**
     * 根据查询条件生成动态省份数据
     */
    generateDynamicProvinceData(baseTime, timeRange, compareDays) {
        const allProvinces = getAllProvinces();
        
        // 根据选中的省份代码过滤
        const filteredProvinces = this.selectedProvinces.length > 0 ? 
            allProvinces.filter(p => this.selectedProvinces.includes(p.code)) : 
            allProvinces.slice(0, 5); // 默认前5个

        // 生成指定天数的数据
        const dateData = [];
        const baseDate = baseTime ? new Date(baseTime) : new Date();
        
        for (let i = compareDays - 1; i >= 0; i--) {
            const currentDate = new Date(baseDate.getTime() - i * 24 * 60 * 60 * 1000);
            const dateStr = currentDate.toLocaleDateString('zh-CN', { 
                month: '2-digit', 
                day: '2-digit' 
            });
            
            // 为每个日期生成各省份的交易量数据，考虑时间范围
            const timeMultiplier = timeRange / 60; // 以1小时为基准
            const provinceData = filteredProvinces.map(prov => ({
                provCode: prov.code,
                provName: prov.name,
                code: prov.code,
                name: prov.name,
                value: Math.floor((Math.random() * 2000 + 800 + i * 50) * timeMultiplier)
            }));

            dateData.push({
                date: dateStr,
                provinceData: provinceData
            });
        }

        return {
            provinces: filteredProvinces.map(p => ({
                ...p,
                provCode: p.code,
                provName: p.name
            })),
            dateData: dateData,
            updateTime: new Date().toLocaleString('zh-CN')
        };
    }

    /**
     * 加载交易量实时数据
     */
    async loadTransactionData() {
        try {
            const timeRange = parseInt($('#transactionTimeRange').val()) || 360;
            const center = $('#transactionCenterSelect').val();
            const servicePlat = $('#transactionServicePlatSelect').val();
            const chelCode = $('#transactionChelCodeSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                data = this.mockData.transaction;
            } else {
                const params = { timeRange, center, servicePlat, chelCode };
                const response = await $.ajax({
                    url: this.config.apiEndpoints.transaction,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            // 创建交易量综合图表
            createTransactionComprehensiveChart('transactionChart', data);
            
            // 更新统计数据
            $('#currentTotalVolume').text(formatNumber(data.currentVolume));
            $('#currentSuccessRate').text(formatPercent(data.currentSuccessRate));
            
            // 计算失败笔数
            const failCount = Math.floor(data.currentVolume * (100 - data.currentSuccessRate) / 100);
            $('#currentFailCount').text(formatNumber(failCount));

            log('info', '交易量数据更新完成');
        } catch (error) {
            handleError(error, '交易量数据加载');
        }
    }

    /**
     * 加载失败响应码数据
     */
    async loadFailCodeData() {
        try {
            const timeRange = parseInt($('#failCodeTimeRange').val()) || 360;
            const limit = parseInt($('#failCodeLimit').val()) || 10;
            const center = $('#failCodeCenterSelect').val();
            const servicePlat = $('#failCodeServicePlatSelect').val();
            
            let data;
            
            if (this.isUsingMockData) {
                data = this.mockData.failCodes;
                // 根据limit参数过滤
                data = {
                    ...data,
                    failCodes: data.failCodes.slice(0, limit)
                };
            } else {
                const params = { timeRange, limit, center, servicePlat };
                const response = await $.ajax({
                    url: this.config.apiEndpoints.failCode,
                    method: 'GET',
                    data: params,
                    timeout: 5000
                });
                data = response.data;
            }

            createFailCodeTrendChart('failCodeChart', data);
            log('info', '失败响应码数据更新完成');
        } catch (error) {
            handleError(error, '失败响应码数据加载');
        }
    }

    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        // 省份交易量环比 - 5分钟刷新
        this.timers.province = setInterval(() => {
            this.loadProvinceData();
        }, this.config.refreshIntervals.province);

        // 交易量监控 - 1分钟刷新
        this.timers.transaction = setInterval(() => {
            this.loadTransactionData();
        }, this.config.refreshIntervals.transaction);

        // 失败响应码 - 1分钟刷新
        this.timers.failCode = setInterval(() => {
            this.loadFailCodeData();
        }, this.config.refreshIntervals.failCode);

        log('info', '自动刷新已启动');
    }

    /**
     * 暂停自动刷新
     */
    pauseAutoRefresh() {
        Object.keys(this.timers).forEach(key => {
            if (this.timers[key]) {
                clearInterval(this.timers[key]);
            }
        });
        log('info', '自动刷新已暂停');
    }

    /**
     * 恢复自动刷新
     */
    resumeAutoRefresh() {
        this.startAutoRefresh();
        log('info', '自动刷新已恢复');
    }

    /**
     * 销毁应用
     */
    destroy() {
        this.pauseAutoRefresh();
        chartManager.disposeAll();
        log('info', '监控应用已销毁');
    }
}

// 全局监控应用实例
let monitorApp;

// 文档加载完成后初始化应用
$(document).ready(function() {
    monitorApp = new MonitorApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (monitorApp) {
        monitorApp.destroy();
    }
});